

#import "AppDelegate.h"
#import "WXApi.h"
#import "ViewController.h"
#import "AFHTTPSessionManager.h"

#define WXPatient_App_ID @"wxd6870b76bf49dd4c"
#define WXPatient_App_Secret @"8765965abd382bd6216b230b11bc3bb1"
#define WX_ACCESS_TOKEN @"access_token"
#define WX_OPEN_ID @"openid"
#define WX_REFRESH_TOKEN @"refresh_token"
#define WX_UNION_ID @"unionid"
#define WX_BASE_URL @"https://api.weixin.qq.com/sns"

@interface AppDelegate ()<WXApiDelegate,NSURLConnectionDataDelegate>


/**
 manager
 */
@property (nonatomic,strong) AFHTTPSessionManager *manager;

@end

@implementation AppDelegate


//.m
+(AppDelegate *)shareDataSource {
    static AppDelegate *dataSource = nil;
    static dispatch_once_t once;
    dispatch_once(&once,^{
        dataSource = [AppDelegate new];
    });
    return dataSource;
}

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [[AFHTTPSessionManager alloc] init];
        
    }
    return _manager;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    ViewController *vc =[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    
    vc.requestForUserInfoBlock = ^() {
        [[AppDelegate shareDataSource] wechatLoginByRequestForUserInfo];
    };
    
    self.window.rootViewController = vc;

    
    [self.window makeKeyAndVisible];
    [self.window setBackgroundColor:[UIColor whiteColor]];
    // 向微信注册
    [WXApi registerApp:WXPatient_App_ID];
    
    return YES;
}

// 授权后回调
// AppDelegate.m
- (void)onResp:(BaseResp *)resp {
    // 向微信请求授权后,得到响应结果
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *temp = (SendAuthResp *)resp;

        NSString *accessUrlStr = [NSString stringWithFormat:@"%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WX_BASE_URL, WXPatient_App_ID, WXPatient_App_Secret, temp.code];
        
        [self.manager GET:accessUrlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"请求access的response = %@", responseObject);
                NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
                NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
                NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
                NSString *refreshToken = [accessDict objectForKey:WX_REFRESH_TOKEN];
                // 本地持久化，以便access_token的使用、刷新或者持续
                if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""]) {
                    [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:WX_ACCESS_TOKEN];
                    [[NSUserDefaults standardUserDefaults] setObject:openID forKey:WX_OPEN_ID];
                    [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:WX_REFRESH_TOKEN];
                    [[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里，来避免数据的丢失
                }
                [self wechatLoginByRequestForUserInfo];
            
            NSLog(@"%s  %d  %@",__func__,__LINE__,@"授权成功");

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"获取access_token时出错 = %@", error);
        }];
        
        NSLog(@"%s  %d  %@",__func__,__LINE__,@"授权失败");
        

    }
}

// AppDelegate.m
// 获取用户个人信息（UnionID机制）
- (void)wechatLoginByRequestForUserInfo {
    
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
    NSString *userUrlStr = [NSString stringWithFormat:@"%@/userinfo?access_token=%@&openid=%@", WX_BASE_URL, accessToken, openID];
    
    [self.manager GET:userUrlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"请求用户信息的response = %@", responseObject);
        
        NSLog(@"%s  %d 请求用户信息的response =  %@",__func__,__LINE__,responseObject);
        
        NSLog(@"%s  %d  %@",__func__,__LINE__,@"登陆成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取用户信息时出错 = %@", error);
        NSLog(@"%s  %d  %@",__func__,__LINE__,@"登陆失败");
    }];
}


-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    return [WXApi handleOpenURL:url delegate:self];
}

#pragma mark WXApiDelegate 微信分享的相关回调

// onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面
- (void)onReq:(BaseReq *)req
{
    NSLog(@"onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面");
}



@end
